<?php

namespace app\admin\model\finance;

use app\common\model\User;
use think\Model;


class Recharge extends Model
{

    

    

    // 表名
    protected $name = 'recharge_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'paytime_text',
        'status_text'
    ];

    public static function init()
    {
        self::afterInsert(function ($row) {});
        self::beforeWrite(function ($row) {});
        self::afterWrite(function ($row) {
            $changedData = $row->getChangedData();
            if (isset($changedData['status'])) {
                if ($changedData['status'] == 'paid') {
                    User::money($row['amount'], $row['user_id'], '充值余额');
                }
            }
        });
        self::beforeDelete(function ($row) {});
    }
    
    public function getStatusList()
    {
        return ['created' => __('Status created'), 'paid' => __('Status paid'), 'expired' => __('Status expired')];
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
